<script setup>
import { getOrderList, getStatistics, takeOrder, rejectionOrder, deliveryOrder, cancelOrder, completeOrder } from '@/api/order.js'
import { useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'

const router = useRouter()

const activeTab = ref('all')
const page = ref(1) //页数
const pageSize = ref(100) //每页数
const total = ref(0) // 零食列表的总条目数量
const loading = ref(false) //数据加载
const allOrderList = ref([]) //数量列表
const orderStatusType = ref({})

const number = ref() //订单号
const phone = ref() //电话
const status = ref() //订单状态

const dialogFormVisible = ref(false) //拒单弹窗
const formLabelWidth = '140px'
const form = ref({
  name: ''
})

const dialogForm = ref(false) //取消弹窗
const formCancel = ref({
  Reason: ''
})

const timeRange = ref([]) //时间
const beginTime = ref('') //开始时间
const endTime = ref('') //结束时间

//时间转换为特定格式（例如 "yyyy-MM-dd HH:mm:ss"）
const formatDateTime = date => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
//选择时间时
const handleSubmit = () => {
  if (timeRange.value.length === 2) {
    beginTime.value = formatDateTime(new Date(timeRange.value[0]))
    endTime.value = formatDateTime(new Date(timeRange.value[1]))
  }
}

onMounted(() => {
  getOrderPage()
  getStatusOrder()
})

//分页查询
const getOrderPage = async () => {
  loading.value = true

  const orderDTO = {
    page: page.value,
    pageSize: pageSize.value,
    status: status.value,
    number: number.value,
    phone: phone.value,
    beginTime: beginTime.value,
    endTime: endTime.value
  }
  console.log(orderDTO)
  const res = await getOrderList(orderDTO)
  console.log('订单', res.data)
  if (res.data.code === 1) {
    allOrderList.value = res.data.data.records
    total.value = res.data.data.total
  }
  loading.value = false
}

//查看订单各种状态统计
const getStatusOrder = async () => {
  const res = await getStatistics()
  console.log(res)
  if (res.data.code === 1) {
    orderStatusType.value = res.data.data
  }
}

//全部订单
const changeAll = () => {
  activeTab.value = 'all'
  status.value = ''
  number.value = ''
  phone.value = ''
  getOrderPage()
}

//待接单
const changePending = () => {
  activeTab.value = 'pending'
  status.value = 2
  getOrderPage()
}

//待派送
const changeDelivery = () => {
  activeTab.value = 'delivery'
  status.value = 3
  getOrderPage()
}

//派送中
const changeGoDelivery = () => {
  activeTab.value = 'godelivery'
  status.value = 4
  getOrderPage()
}

//已完成
const changeFinish = () => {
  activeTab.value = 'finish'
  status.value = 5
  getOrderPage()
}

//取消
const changeCancelled = () => {
  activeTab.value = 'cancelled'
  status.value = 6
  getOrderPage()
}

//查看订单详情
const getOrderDetail = id => {
  router.push({ path: '/order/detail', query: { id } })
}

//接单
const goPending = async data => {
  const ordersConfirmDTO = {
    id: data.id
  }
  const res = await takeOrder(ordersConfirmDTO)
  if (res.data.code === 1) {
    ElMessage.success('接单成功！')
    getOrderPage()
  }
}

//拒单
const refuseOrder = data => {
  dialogFormVisible.value = true
  form.value.id = data.id
}
//拒单弹窗
const judan = async () => {
  const ordersConfirmDTO = {
    id: form.value.id,
    rejectionReason: form.value.name
  }
  const res = await rejectionOrder(ordersConfirmDTO)
  console.log(res.data)
  if (res.data.code === 1) {
    dialogFormVisible.value = false
    getOrderPage()
    ElMessage.success('接单成功！')
  }
}

//派送
const Delivery = async id => {
  console.log(id)
  const res = await deliveryOrder(id)
  console.log(res.data)
  if (res.data.code === 1) {
    getOrderPage()
    ElMessage.success('派送成功！')
  }
}

//取消
const Cancel = data => {
  dialogForm.value = true
  formCancel.value.id = data.id
}
//取消弹窗
const Confirm = async () => {
  const ordersCancelDTO = {
    cancelReason: formCancel.value.Reason
  }
  const res = await cancelOrder(ordersCancelDTO)
  console.log(res.data)
  if (res.data.code === 1) {
    dialogForm.value = false
    getOrderPage()
    ElMessage.success('取消成功！')
  }
}

//完成
const complete = async id => {
  const res = await completeOrder(id)
  console.log(res.data)
  if (res.data.code === 1) {
    getOrderPage()
    ElMessage.success('已完成！')
  }
}
</script>

<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="tab-container">
        <div :class="{ active: activeTab === 'all' }" @click="changeAll">全部订单</div>
        <div :class="{ active: activeTab === 'pending' }" @click="changePending">待接单 <span>{{ orderStatusType.toBeConfirmed }}</span></div>
        <div :class="{ active: activeTab === 'delivery' }" @click="changeDelivery">待派送 <span>{{orderStatusType.confirmed}}</span></div>
        <div :class="{ active: activeTab === 'godelivery' }" @click="changeGoDelivery">派送中 <span>{{ orderStatusType.deliveryInProgress }}</span></div>
        <div :class="{ active: activeTab === 'finish' }" @click="changeFinish">已完成</div>
        <div :class="{ active: activeTab === 'cancelled' }" @click="changeCancelled">已取消</div>
      </div>

      <div class="tableBar">
        <label style="margin-right: 10px">订单号：</label>
        <el-input v-model="number" placeholder="请填写订单号" style="width: 15%" clearable @clear="getOrderPage()" @keyup.enter.native="getOrderPage()" />
        <label style="margin-right: 5px; margin-left: 20px">手机号：</label>
        <el-input v-model="phone" placeholder="请填手机号" style="width: 15%" clearable @clear="getOrderPage()" @keyup.enter.native="getOrderPage()" />
        <label style="margin-right: 5px; margin-left: 20px">订单时间：</label>

        <el-date-picker v-model="timeRange" type="datetimerange" start-placeholder="开始" end-placeholder="结束" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" @change="handleSubmit" />

        <div style="float: right">
          <el-button type="primary" round @click="getOrderPage">
            查询
          </el-button>
        </div>
      </div>

      <div v-if="activeTab === 'all'">
        <!-- 显示全部订单内容 -->
        <el-table v-loading="loading" :data="allOrderList" stripe class="tableBox" @selection-change="handleSelectionChange">
          <el-table-column prop="number" label="订单号" />
          <el-table-column label="订单状态">
            <template #default="scope">
              <div class="tableColumn-status">
                <span v-if="scope.row.status === 1">待付款</span>
                <span v-else-if="scope.row.status === 2">待接单</span>
                <span v-else-if="scope.row.status === 3">待派送</span>
                <span v-else-if="scope.row.status === 4">派送中</span>
                <span v-else-if="scope.row.status === 5">已完成</span>
                <span v-else-if="scope.row.status === 6">已取消</span>
                <!-- <span v-else-if="scope.row.status === 7">退款</span> -->
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="amount" label="金额(元)" />
          <el-table-column prop="orderTime" label="下单时间" />
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 2">
                <el-button type="text" size="small" class="blueBug" @click=" goPending(scope.row)">
                  接单
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="refuseOrder(scope.row)">
                  拒单
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
              <span v-if="scope.row.status === 3">
                <el-button type="text" size="small" class="blueBug" @click="Delivery(scope.row.id)">
                  派送
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="Cancel(scope.row)">
                  取消
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
              <span v-if="scope.row.status === 4">
                <el-button type="text" size="small" class="blueBug" @click="complete(scope.row.id)">
                  完成
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="Cancel(scope.row)">
                  取消
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
              <span v-if="scope.row.status === 5">
                <!-- <el-button type="text" size="small" class="blueBug" @click="">
                  退单
                </el-button> -->
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
              <span v-if="scope.row.status === 6">
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>

            </template>

          </el-table-column>
        </el-table>
      </div>

      <div v-if="activeTab === 'pending'">
        <!-- 显示待接单订单内容 -->
        <el-table v-loading="loading" :data="allOrderList" stripe class="tableBox" @selection-change="handleSelectionChange">
          <el-table-column prop="number" label="订单号" />
          <el-table-column label="零食名称">
            <template #default="scope">
              <div>
                <span v-for="(detail, index) in scope.row.orderDetailList" :key="index">
                  {{ detail.name }}
                  <!-- 如果需要在每个name后面添加分隔符，可以在插值表达式中添加 -->
                  <span v-if="index !== scope.row.orderDetailList.length - 1">, </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="estimatedDeliveryTime" label="预计送达时间" />
          <el-table-column prop="amount" label="金额" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 2">
                <el-button type="text" size="small" class="blueBug" @click="goPending(scope.row)">
                  接单
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="refuseOrder(scope.row)">
                  拒单
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="activeTab === 'delivery'">
        <!-- 显示待派送订单内容 -->
        <el-table v-loading="loading" :data="allOrderList" stripe class="tableBox" @selection-change="handleSelectionChange">
          <el-table-column prop="number" label="订单号" />
          <el-table-column label="零食名称">
            <template #default="scope">
              <div>
                <span v-for="(detail, index) in scope.row.orderDetailList" :key="index">
                  {{ detail.name }}
                  <!-- 如果需要在每个name后面添加分隔符，可以在插值表达式中添加 -->
                  <span v-if="index !== scope.row.orderDetailList.length - 1">, </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="estimatedDeliveryTime" label="预计送达时间" />
          <el-table-column prop="amount" label="金额" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 3">
                <el-button type="text" size="small" class="blueBug" @click="Delivery(scope.row.id)">
                  派送
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="Cancel(scope.row)">
                  取消
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="activeTab === 'godelivery'">
        <!-- 显示派送中订单内容 -->
        <el-table v-loading="loading" :data="allOrderList" stripe class="tableBox" @selection-change="handleSelectionChange">
          <el-table-column prop="number" label="订单号" />
          <el-table-column label="零食名称">
            <template #default="scope">
              <div>
                <span v-for="(detail, index) in scope.row.orderDetailList" :key="index">
                  {{ detail.name }}
                  <!-- 如果需要在每个name后面添加分隔符，可以在插值表达式中添加 -->
                  <span v-if="index !== scope.row.orderDetailList.length - 1">, </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="estimatedDeliveryTime" label="预计送达时间" />
          <el-table-column prop="amount" label="金额" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 4">
                <el-button type="text" size="small" class="blueBug" @click="complete(scope.row.id)">
                  完成
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="Cancel(scope.row)">
                  取消
                </el-button>
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="activeTab === 'finish'">
        <!-- 显示已完成订单内容 -->
        <el-table v-loading="loading" :data="allOrderList" stripe class="tableBox" @selection-change="handleSelectionChange">
          <el-table-column prop="number" label="订单号" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="estimatedDeliveryTime" label="送达时间" />
          <el-table-column prop="amount" label="金额" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 5">
                <!-- <el-button type="text" size="small" class="blueBug" @click="">
                  退单
                </el-button> -->
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
            </template>

          </el-table-column>
        </el-table>
      </div>

      <div v-if="activeTab === 'cancelled'">
        <!-- 显示已取消订单内容 -->
        <el-table v-loading="loading" :data="allOrderList" stripe class="tableBox" @selection-change="handleSelectionChange">

          <el-table-column prop="number" label="订单号" />

          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="orderTime" label="下单时间" />
          <el-table-column prop="cancelTime" label="取消时间" />
          <el-table-column prop="cancelReason" label="取消原因" />
          <el-table-column label="操作" width="250" align="center">
            <template #default="scope">
              <span v-if="scope.row.status === 6">
                <el-button type="text" size="small" class="blueBug" @click="getOrderDetail(scope.row.id)">
                  查看
                </el-button>
              </span>
            </template>

          </el-table-column>
        </el-table>
      </div>

      <!-- 弹窗拒单 -->
      <el-dialog v-model="dialogFormVisible" title="拒单" width="500">
        <el-form :model="form">
          <el-form-item label="拒单原因" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="judan">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 取消弹窗 -->
      <el-dialog v-model="dialogForm" title="取消订单" width="500">
        <el-form :model="formCancel">
          <el-form-item label="取消原因" :label-width="formLabelWidth">
            <el-input v-model="formCancel.Reason" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogForm = false">取消</el-button>
            <el-button type="primary" @click="Confirm">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>

    </div>

    <div class="demo-pagination-block">

      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[2, 4, 10, 40]" :background="background" layout="total, sizes, prev, pager, next, jumper," :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页" />

    </div>

  </div>
</template>

<style lang="scss" scoped>
.dashboard-container {
  margin: 10px;
  .container {
    background: #fff;
    position: relative;
    z-index: 1;
    padding: 30px 28px;
    border-radius: 4px;

    .tab-container {
      display: flex;
      justify-content: space-around;
      padding: 10px;
      background-color: #fff8f8;

      span {
        color: #9a2929;
        font-size: 18px;
      }

      div {
        cursor: pointer;
      }

      .active {
        font-weight: bold;
        color: blue;
      }
    }

    .tableBar {
      display: inline-block;
      width: 100%;
      margin-bottom: 20px;
    }
  }

  .demo-pagination-block {
    margin-top: 30px;
    float: right;
  }
}
</style>